<script setup>
  import { addDayRcomApi } from '@/api/article'
  import LvCitySelect from '@/components/LvCitySelect.vue'
  import LvUpload from '@/components/LvUpload.vue'
  import { ElMessage } from 'element-plus'
  import { reactive, readonly, ref } from 'vue'
  const emit = defineEmits(['update'])

  const visible = ref(false)
  const form = reactive({
    title: '',
    address: '',
    color: '',
    imageUrl: ''
  })
  const formRef = ref(null)
  const rules = readonly({
    title: [{ message: '标题不能为空', required: true, trigger: 'blur' }],
    address: [{ message: '地址不能为空', required: true, trigger: 'blur' }],
    color: [{ message: '颜色不能为空', required: true, trigger: 'blur' }]
  })

  const onSubmit = async () => {
    try {
      await formRef.value.validate()
      // 验证图片是否上传
      if (!form.imageUrl) return ElMessage.error('请上传图片!!!')
      // 提交数据
      await addDayRcomApi(form)
      // 关闭弹窗  更新数据
      ElMessage.success('操作成功')
      emit('update')
      close()
    } catch (error) {
      console.log('验证失败')
    }
  }

  const citySelectRef = ref(null)

  const open = () => {
    visible.value = true
  }

  const close = () => {
    formRef.value.resetFields()
    form.imageUrl = ''
    citySelectRef.value.cityOptions = []
    visible.value = false
  }

  defineExpose({
    open,
    close
  })
</script>

<template>
  <el-dialog v-model="visible" title="新增推荐" width="60%" :before-close="close">
    <div class="dialog-view">
      <!-- 左边上传内容 -->
      <div class="upload-view">
        <!-- vue3中props为key  抛出的事件为update:key 则可以使用v-model做绑定 -->
        <LvUpload v-model:image-url="form.imageUrl" />
      </div>
      <!-- 右边表单内容 -->
      <div class="form-view">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" label-position="left" size="large">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="输入标题"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <LvCitySelect ref="citySelectRef" v-model="form.address" />
          </el-form-item>
          <el-form-item label="颜色值" prop="color">
            <el-color-picker v-model="form.color" show-alpha />
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="onSubmit" class="submit-btn">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
  .dialog-view {
    display: flex;
    justify-content: center;
    padding-bottom: 80px;
    padding-top: 40px;
    .upload-view {
    }
    .form-view {
      width: 400px;
      margin-left: 40px;
      .submit-btn {
        width: 80%;
      }
    }
  }
</style>
